//
//  BasePageViewController.swift
//  SwiftScienceChina
//
//  Created by 贾培军 on 2020/1/9.
//  Copyright © 2020 贾培军. All rights reserved.
//

import UIKit
import ESPullToRefresh

typealias BlockDataArrayChanged = (_ appendArray: NSMutableArray)->()

open class SWBasePageViewController: SWBaseViewController {
    lazy var dataArray = NSMutableArray()
    var heightArray = [CGFloat]()
    var contentView = UIView()
    var bIsGroupedTableViewStyle = false
    var notAutoFirstRequest = false
    var blockFirstHeaderFetcher:BlockDataArrayChanged?
    var blockMoreFootFetch:BlockDataArrayChanged?
    var blockDataArrayChanged:BlockDataArrayChanged?
    var dataFetcher:SWBasePageListFetcher?
    var scrollView:Any?
    
    var pullHeader: ESRefreshHeaderAnimator {
        get {
            let h = ESRefreshHeaderAnimator.init(frame: CGRect.zero)
            h.pullToRefreshDescription = "下拉刷新"
            h.releaseToRefreshDescription = "松开获取最新数据"
            h.loadingDescription = "下拉刷新..."
            return h
        }
    }
    var pullFooter: ESRefreshFooterAnimator {
        get {
            let f = ESRefreshFooterAnimator.init(frame: CGRect.zero)
            f.loadingMoreDescription = "上拉加载更多"
            f.noMoreDataDescription = "没有更多了"
            f.loadingDescription = "加载更多..."
            return f
        }
    }
    
    weak var requestDelegate: SWPageListRequestDelegate?
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    required public init?(coder aCoder: NSCoder) {
        super.init(coder: aCoder)
        NSLog("%@", #function)
    }
    
    
    func startLoading() {
        
    }
    
    func endLoading() {
        
    }
    
    func reloadAndReset() {
        
    }
    
    func reload() {
        
    }
    
    func checkHasMoreWithCount(total: NSInteger) {
        
    }
    
    func endHeader() {
        
    }
    
    func endFooter() {
        
    }
    
    func firstPageFetch() {
        if self.dataFetcher == nil {
            return
        }
        self.startLoading()
        self.dataFetcher?.stop()
        self.requestDelegate?.requestWillRefresh()
        self.dataFetcher?.startWithBlock(completeBlock: ({ [weak self] (total: NSInteger, retItemArray: NSArray?, error: NSError?) in
            guard let self = self else { return }
            self.endLoading()
            self.requestDelegate?.requestEndRefreshWithError(error: error)
            self.endHeader()
            if let error = error {
                self.dataErrorView.title = error.localizedDescription
                return
            }
            self.blockFirstHeaderFetcher?(retItemArray!.mutableCopy() as! NSMutableArray)
            let data = SWUnhandledRequestData()
            data.requestDataExist = retItemArray!.count != 0
            data.localDataExist = self.dataArray.count != 0
            if self.handleRequestData(data: data, view: self.contentView){
                self.dataArray.removeAllObjects()
                self.dataArray.addObjects(from: retItemArray as! [Any])
                self.reloadAndReset()
                return
            }
            self.dataArray.removeAllObjects()
            self.heightArray.removeAll()
            self.dataArray.addObjects(from: retItemArray as! [Any])
            self.blockDataArrayChanged?(retItemArray!.mutableCopy() as! NSMutableArray)
            //save Cache
            self.reloadAndReset()
            self.checkHasMoreWithCount(total: total)
        }))
    }
    
    func morePageFetch() {
        self.dataFetcher?.stop()
        self.requestDelegate?.requestWillFetchMore()
        self.startLoading()
        self.dataFetcher?.startWithBlock(completeBlock: { [weak self] (total: NSInteger, retItemArray: NSArray?, error: NSError?) in
            guard let self = self else { return }
            self.endLoading()
            self.requestDelegate?.requestEndRefreshWithError(error: error)
            guard error == nil else {
                self.view.makeToast(error?.localizedDescription)
//                self.showToast(error!.localizedDescription)
                self.endFooter()
                return
            }
            let addData = {
                self.blockDataArrayChanged?(retItemArray?.mutableCopy() as! NSMutableArray)
                self.dataArray.addObjects(from: retItemArray as! [Any] )
                self.reload()
                self.checkHasMoreWithCount(total: total)
            }
            // mainThread
            addData()
            })
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        self.view.addSubview(self.contentView)
        self.contentView.snp.makeConstraints { (m) in
            m.edges.equalTo(UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0))
        }
        self.emptyView.retryBlock = {[weak self] ()->Void in
            guard let `self` = self else { return }
            self.firstPageFetch()
        }
        self.errorView.retryBlock = {[weak self] ()->Void in
            guard let `self` = self else { return }
            self.firstPageFetch()
        }
        self.requestDelegate = self.dataFetcher;
        if !self.notAutoFirstRequest {
            self.firstPageFetch()
        }
        // Do any additional setup after loading the view.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
